package zengjin.test;

import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.*;
import java.net.URLEncoder;

/**
 * @author 19324
 */
@Tag(name = "文件相关接口")
@RestController
@RequestMapping("/fragmentFile")
@Slf4j
public class DownLoadController {
    private static final String utf8 = "utf-8";

    @GetMapping("/download")
    public void download(HttpServletRequest request, HttpServletResponse response) throws Exception {

        File file = new File("D:\\test\\测试存储.zip");
        response.setCharacterEncoding(utf8);

        InputStream inputStream = null;
        OutputStream outputStream = null;

        try {
            //分片下载
            //1.获取到文件的长度
            long fSize = file.length();
            //2.设置响应头信息
            response.setContentType("application/octet-stream");
            String fileName = URLEncoder.encode(file.getName(), utf8);
            response.addHeader("Content-Disposition", "attachment;filename=" + fileName);

            response.setHeader("Accept-Range", "bytes");
            response.setHeader("fSize", String.valueOf(fSize));
            response.setHeader("fileName", String.valueOf(fileName));

            long start = 0;
            long end = fSize - 1;
            long sum = 0;

            if (request.getHeader("Range") != null) {
                log.info("要分片下载");
                response.setStatus(206);
                String range = request.getHeader("Range").replaceAll("bytes=", "");
                String[] rangeArr = range.split("-");
                if (rangeArr.length == 2) {
                    start = Long.parseLong(rangeArr[0].trim());
                    end = Long.parseLong(rangeArr[1].trim());
                    if (end > fSize - 1) {
                        end = fSize - 1;
                    }
                } else {
                    start = Long.parseLong(range.replaceAll("bytes=", "").trim());
                }

            }
            long len = end - start + 1;
            String contentRange = "bytes " + start + "-" + end + "/" + fSize;
            response.setHeader("Content-Range", contentRange);
            response.setHeader("Content-Length", String.valueOf(len));

            outputStream = new BufferedOutputStream(response.getOutputStream());
            inputStream = new BufferedInputStream(new FileInputStream(file));

            inputStream.skip(start);
            byte[] bytes = new byte[1024];
            int length = 0;
            while (sum < len) {
                log.info("分片下载中");
                length = inputStream.read(bytes, 0, (len - sum) <= bytes.length ? (int) ((int) len - sum) : bytes.length);
                sum += length;
                outputStream.write(bytes, 0, length);

            }
            log.info("下载成功");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                inputStream.close();
            }
            if (outputStream != null) {
                outputStream.close();
            }
        }


    }
}
